package controller

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"

	comm "main/comm"
	"main/model"
)

func AccountList(w http.ResponseWriter, r *http.Request) {
	as, err := comm.GetAccountsAscId()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusOK)
		if err := json.NewEncoder(w).Encode(as); err != nil {
			panic(err)
		}
	}
}

func AccountShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	if aid, err := strconv.ParseInt(vars["Id"], 10, 64); err != nil {
		w.WriteHeader(http.StatusBadRequest)
	} else {
		a, err2 := comm.GetAccount(aid)
		if err2 != nil {
			w.WriteHeader(http.StatusInternalServerError)
		} else {
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(http.StatusOK)
			if err := json.NewEncoder(w).Encode(a); err != nil {
				w.WriteHeader(http.StatusInternalServerError)
			}
		}
	}
}

func AccountCreate(w http.ResponseWriter, r *http.Request) {
	var ac model.Account
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	}
	if err := r.Body.Close(); err != nil {
		w.WriteHeader(http.StatusInternalServerError)
	}
	if err := json.Unmarshal(body, &ac); err != nil {
		w.Header().Set("Content-Type", "application/json;   charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	_, err = comm.GetAccount(ac.Id)
	if err == nil {
		if err = comm.UpdateAccount(&ac); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		} else {
			w.WriteHeader(http.StatusOK)
		}
	} else {
		if err = comm.NewAccount(&ac); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		} else {
			w.WriteHeader(http.StatusOK)
		}
	}
}
